<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card>
      <!-- 添加用户 -->
      <div style="margin-top: 15px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入内容"
                      v-model="queryList.query"
                      clearable
                      @clear="getUserInfo">
              <el-button slot="append" 
              icon="el-icon-search"
              @click="getUserInfo"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 添加用户对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="50%"
          @close="addDialogClosed">
          <!-- 内容主题区域 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog
          title="修改用户信息"
          :visible.sync="editDialogVisible"
          width="50%"
          @close="editDialogClosed">
          <!-- 修改内容区 -->
          <el-form :model="editForm" 
                   :rules="editFormRules" 
                   ref="editFormRef" 
                   label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
             <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
             <el-form-item label="手机" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 用户列表区域 -->
      <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe>
        <el-table-column
          type="index"
          label="#">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>  
        <el-table-column
          prop="mg_state"
          label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state" 
              @change="stateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" 
                       icon="el-icon-edit" 
                       style="margin-right = 6px"
                       circle @click="editClick(scope.row.id)">
            </el-button>
            <!-- 删除用户按钮 -->
            <el-popconfirm title="确认删除用户吗？"
                           @onConfirm="comfirmDelete(scope.row.id)"
                           @onCancel="cancelDelete">
              <el-button type="danger" icon="el-icon-delete" circle slot="reference" @click="deleteUserClick"></el-button>
            </el-popconfirm>
            <el-tooltip effect="dark" 
                        content="分配角色" 
                        placement="top" 
                        :enterable="false" >
              <el-button type="warning" 
                         icon="el-icon-star-off"
                         circle
                         @click="setRoles(scope.row)">
               </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryList.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>   
    </el-card>
    <!-- 分配角色Dialog框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialog"
      width="50%"
      @close="setDialogClosed">
      <div>
        <p>当前的用户：{{this.userInfo.username}}</p>
        <p>当前的角色： {{this.userInfo.role_name}}</p>
        <span>分配新角色</span>
         <el-select v-model="setNewRoles" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.roleName">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmSetRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义手机号规则
    var checkMobile = (rule,value,callback) => {
      const regMobile = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
      if(regMobile.test(value)) {
        return callback();
      }
      callback(new Error('请输入合法的手机号'));
    }
    // 定义邮箱规则
    var checkEmail = (rule,value,callback) => {
      const regEmail =  /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if(regEmail.test(value)) {
        return callback();
      }
      callback(new Error('请输入合法的邮箱'));
    }
    return {
      queryList : {
        query:'',
        pagenum: 1,
        pagesize: 2
      },
      // 控制添加对话框打开关闭
      dialogVisible: false,
      // 控制修改对话框打开关闭
      editDialogVisible: false,
      // 添加数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改数据
      editForm: {},
      // 添加数据验证规则
      addFormRules: {
        username: [
          {
            required: true, message: '请输入用户名',
            trigger: 'blur'
            },
          {
            max:10,min:3,message:"请输入3到10个字符",
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码',
            trigger: 'blur'
            },
          {
            max:18,min:6,message:"请输入6到18个字符",
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '请输入邮箱',
            trigger: 'blur'
          },
          { 
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入手机号',
            trigger: 'blur'
          },
          { 
            validator: checkMobile, trigger: 'blur'
          }
        ]
      },
      // 修改表单验证
      editFormRules: {
        email:[
          {
            required: true, message: '请输入邮箱',
            trigger: 'blur'
          },
          { 
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入手机号',
            trigger: 'blur'
          },
          { 
            validator: checkMobile, trigger: 'blur'
          }
        ]
      },
      total: 0,
      userList: [],  //后台数据被改
      // 控制分配角色Dialog开关
      setRolesDialog: false,
      userInfo: {},
      rolesList: [],
      setNewRoles: '',
    }
  },
  created () {
    this.getUserInfo();
  },
  methods: {
    async getUserInfo () {
      const {data : res} = await this.$http.get('users',{params:this.queryList})
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.userList = res.data.users;
        this.total = res.data.total;
        console.log(this.total);
      }
    },
    // 监听pageSize变化的事件
    handleSizeChange (newSize) {
      this.queryList.pagesize = newSize;
      // 重新发起请求
      this.getUserInfo();
    },
    // 监听页码值发生改变
    handleCurrentChange (newPage) {
      this.queryList.pagenum = newPage;
      this.getUserInfo();
    },
    // 状态改变
    async stateChange (stateInfo) {
      const {data:res} = await this.$http.put(
        `users/${stateInfo.id}/state/${stateInfo.mg_state}`)
        // console.log(res);
      if(res.meta.status !== 200) {
        stateInfo.mg_state = !stateInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      } else {
        this.$message.success("更新状态成功");
      }
    },
    // 监听添加用户事件的关闭按钮
    addDialogClosed () {
      this.$refs.addFormRules.resetFields();
    },
    // 监听添加用户确认按钮，进行表单预验证
    addUser () {
      this.$refs.addFormRules.validate(async valid => {
        if(!valid) return 
        // 发起添加网络验证的请求
        const {data:res} = await this.$http.post('users',this.addForm);
        if(res.meta.status !== 201) {
          this.$message.error('请求失败');
        } 
        this.$message.success('请求成功');
        this.dialogVisible = false;
        this.getUserInfo();
      })
    },
    // 修改用户信息，编辑按钮，
    async editClick (id) {
      this.editDialogVisible = true;
      // 获取前台ID，字符串拼接的形式发送到后台
      const {data:res} = await this.$http.get('users/' + id)
     if(res.meta.status !== 200) 
     return this.$message.error("查询ID失败");
     this.editForm = res.data;
    },
    // 关闭修改对话框时重置数据
    editDialogClosed () {
      this.$refs.editFormRef.resetFields();
    },
    // 在修改之前进行表单验证
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return 
        const {data:res} = await this.$http.put('users/' + this.editForm.id,
        {mobile: this.editForm.mobile,
        email: this.editForm.email})
        if(res.meta.status !== 200) return this.$message.error("更新数据失败");
        this.getUserInfo();
        this.editDialogVisible = false;
      })
    },
    // 删除按钮
    deleteUserClick () {
      console.log("11111");
    },
    async comfirmDelete(id) {
      const {data:res} = await this.$http.delete('users/' + id);
      if(res.meta.status !== 200) return this.$message.error('删除失败');
      this.$message.success(res.meta.msg);
      this.getUserInfo();
    },
    cancelDelete() {
      console.log(22222);
    },
    async setRoles(userInfo) {
      this.userInfo = userInfo;
      const {data: res} = await this.$http.get('roles')
      if(res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败")
      }
      this.rolesList = res.data;
      console.log(this.rolesList);
      this.setRolesDialog = true;
    },
    async confirmSetRoles() {
      if(!this.setNewRoles) {
        return this.$message.error("为分配新的角色")
      }
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,
      {rid: this.setNewRoles});
      if(res.meta.status !== 200) {
        return this.$message.error("获取分配角色列表失败") 
      }
      this.getUserInfo();
      this.setRolesDialog = false
    },
    setDialogClosed() {
      this.setNewRoles = '';
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
// .action {
//   display: flex;
//   justify-content: space-between;
// }
</style>>
